use crate::core::generate_source;
use crate::core::global_args::Args;
use clap::Parser;
use include_dir::{include_dir, Dir};
use std::env::current_dir;
use std::path::PathBuf;
use std::process;
use wang_utils::git::{git_add, git_commit, git_init};

pub mod core;

static TEMPLATE_DIR: Dir<'_> = include_dir!("src/template");

fn main() {
    let args = Args::parse();
    check_folder_exists(&args);
    if let Err(e) = generate_source(&TEMPLATE_DIR, &args) {
        eprintln!("出错了:{e:?}");
        process::exit(1);
    }
    println!("代码生成完毕");
    if args.git {
        if let Err(e) = init_git_folder(&args) {
            eprintln!("初始化git仓库出错:{e:?}");
            process::exit(1);
        }
        println!("初始化git仓库成功");
    }
}

fn init_git_folder(args: &Args) -> anyhow::Result<()> {
    let path = PathBuf::new();
    let dir = current_dir()?;
    let path = path.join(dir);
    let path = path.join(args.name.clone());
    // git init
    let repo = git_init(path)?;
    // git add .
    git_add(&repo)?;
    // git commit -m "initial commit"
    git_commit(&repo, "initial commit")?;
    Ok(())
}

fn check_folder_exists(args: &Args) {
    let project_name = args.name.as_str();
    //获取当前目录
    let current_folder = current_dir().unwrap();
    let output_folder = current_folder.join(project_name);
    if output_folder.exists() {
        eprintln!("目录已经存在，取消操作");
        process::exit(1);
    }
}
